import { SortProps } from "../hooks/useBillboards";

interface ReorderProps extends SortProps {
  list: { id: number }[];
}

export const reorder = ({ list, fromId, referenceId, type }: ReorderProps) => {
  const fromIdx = list.findIndex((item) => item.id === fromId);
  if (referenceId === undefined)
    return insert(list, fromIdx, list.length - 1, "after");
  const toIdx = list.findIndex((item) => item.id === referenceId);
  return insert(list, fromIdx, toIdx, type);
};

export const insert = (
  list: unknown[],
  fromIdx: number,
  toIdx: number,
  type: "before" | "after"
) => {
  let result = [...list];
  const toItem = result[toIdx];
  const fromItem = result.splice(fromIdx, 1)[0];
  const referenceIdx = result.indexOf(toItem);
  result.splice(
    type === "before" ? referenceIdx : referenceIdx + 1,
    0,
    fromItem
  );
  return result;
};
